package middleware

import (
	"strings"
	"time"
	"yuanxin-admin/internal/dto"
	"yuanxin-admin/internal/model"
	"yuanxin-admin/internal/repository"

	"gitee.com/botaoshow/yuanxin/web/y"
	"github.com/gin-gonic/gin"
)

// LoginLog 登录日志
func LoginLog() gin.HandlerFunc {
	return func(c *gin.Context) {
		var d dto.SysUserLoginDto
		_ = c.ShouldBindBodyWithJSON(&d)
		// 继续处理请求
		c.Next()
		// 创建登录日志记录
		log := &model.SysLoginLog{
			Username:  d.Username,
			IP:        c.ClientIP(),
			Address:   stringPtr(getClientAddress(c)),
			Browser:   stringPtr(getBrowserInfo(c)),
			Os:        stringPtr(getOSInfo(c)),
			Status:    getLoginStatus(c),
			Msg:       stringPtr(getLoginMessage(c)),
			LoginTime: time.Now(),
		}

		// 异步保存日志以避免阻塞主请求
		go func() {
			err := repository.SysLoginLog.WithContext(c).Create(log)
			if err != nil {
				y.Error(err.Error())
			}
		}()
	}
}

// 字符串指针辅助函数
func stringPtr(s string) *string {
	return &s
}

// getClientAddress 获取客户端地址
func getClientAddress(c *gin.Context) string {
	// 可以通过IP地理位置库来获取具体地址
	ip := c.ClientIP()
	// 简单实现，实际可以调用IP定位服务
	return ip
}

// getBrowserInfo 获取浏览器信息
func getBrowserInfo(c *gin.Context) string {
	userAgent := c.GetHeader("User-Agent")
	if userAgent == "" {
		return "未知"
	}
	if strings.Contains(userAgent, "Edg") {
		return "Edge"
	} else if strings.Contains(userAgent, "Chrome") {
		return "Chrome"
	} else if strings.Contains(userAgent, "Firefox") {
		return "Firefox"
	} else if strings.Contains(userAgent, "Safari") {
		return "Safari"
	} else if strings.Contains(userAgent, "Opera") || strings.Contains(userAgent, "OPR") {
		return "Opera"
	} else if strings.Contains(userAgent, "MicroMessenger") {
		return "微信"
	} else {
		return "未知"
	}
}

// getOSInfo 获取操作系统信息
func getOSInfo(c *gin.Context) string {
	userAgent := c.GetHeader("User-Agent")
	if userAgent == "" {
		return "未知"
	}
	if strings.Contains(userAgent, "Windows NT") {
		return "Windows"
	} else if strings.Contains(userAgent, "Mac OS") {
		return "Mac OS"
	} else if strings.Contains(userAgent, "Linux") {
		return "Linux"
	} else if strings.Contains(userAgent, "Android") {
		return "Android"
	} else if strings.Contains(userAgent, "iPhone") || strings.Contains(userAgent, "iPad") {
		return "iOS"
	} else {
		return "未知"
	}
}

// getLoginStatus 获取登录状态
func getLoginStatus(c *gin.Context) string {
	// 根据HTTP状态码判断登录是否成功
	if c.Writer.Status() >= 200 && c.Writer.Status() < 400 {
		return "0"
	}
	return "1" // 失败
}

// getLoginMessage 获取登录消息
func getLoginMessage(c *gin.Context) string {
	// 根据状态码返回相应消息
	status := c.Writer.Status()
	switch {
	case status >= 200 && status < 300:
		return "登录成功"
	case status >= 400 && status < 500:
		return "客户端错误"
	case status >= 500:
		return "服务器错误"
	default:
		return "未知状态"
	}
}
